package com.damon.thread;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import com.damon.Entity.WcsDvcEntity;
import com.damon.log.WcsLog;
import com.damon.utils.DbUtil;
import com.damon.utils.LogUtil;

/**
 * 该线程调用存储过程,在线程池中使用
 * @author 风蚕
 *
 */
public class ProcedureThread extends Thread {
	
	private WcsLog logger;
	
	WcsDvcEntity wcs;//设备整体信息
	OutputStream os;//输出流
	String msg;//plc报文
	long readStartTime;//读取到plc报文的时间
	
	public ProcedureThread(WcsDvcEntity wcs,OutputStream os,String msg,long readStartTime) {
		this.wcs = wcs;
		this.os = os;
		this.msg = msg;
		this.readStartTime = readStartTime;
		this.logger = LogUtil.getLogger(ProcedureThread.class, wcs);
	}
	
	@Override
	public void run() {
		Connection conn = null;
		try {
			conn = DbUtil.getConnection();
			String sql = "{call " + wcs.getRevProc() + "(?,?,?,?,?,?)}";
			CallableStatement procedureCallable  = conn.prepareCall(sql);
			procedureCallable.setInt(1, wcs.getDvcId());//plc的设备号
			procedureCallable.setString(2, msg);//plc发来的报文
			procedureCallable.registerOutParameter(3, Types.VARCHAR);//回复给plc的报文
			procedureCallable.registerOutParameter(4, Types.INTEGER);//上一次数据包序号
			procedureCallable.registerOutParameter(5, Types.VARCHAR);//调用结果：0，成功；其他，数据错误代码
			procedureCallable.registerOutParameter(6, Types.LONGVARCHAR);//返回给调用程序的提示信息
			procedureCallable.execute();
			String forPlcMsg = procedureCallable.getString(3);
			String forAppMsg = procedureCallable.getString(6);
//			logger.info(procedureCallable.getString(4));
//			logger.info(procedureCallable.getString(5));
			if (forPlcMsg.length() != 0) {
				os.write(Hex.decodeHex(forPlcMsg));
			}
//			if (!forAppMsg.equals("")) {
//				logger.info("存储过程返回信息："+forAppMsg);
//			}
			logger.info("向plc返回报文："+forPlcMsg);
			logger.info("日志信息："+forAppMsg);
			logger.info("time："+ ( System.currentTimeMillis() - readStartTime)+"\n");
			
		} catch (SQLException e) {
			logger.error("数据库错误，存储过程连接调用失败！",e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("io流写出失败",e);
			e.printStackTrace();
		} catch (DecoderException e) {
			logger.error("16进制转化失败！",e);
			e.printStackTrace();
		}finally {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.error("connection连接关闭失败！",e);
				e.printStackTrace();
			}
		}
		
		
	}
}

